package com.huixi.config.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;

@Component
@WebFilter(filterName = "gloableFilter", urlPatterns = "/*")
public class GloableFilter implements Filter {

	// private JwtProperties jwtProperties;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	/*@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
	    HttpServletRequest request = (HttpServletRequest) req;
	    HttpServletResponse response = (HttpServletResponse) res;
	    String contextPath = request.getContextPath();
	    String requestUrl = request.getRequestURL().toString();
	
	    request.setAttribute("contextPath", contextPath);
	    jwtProperties = (JwtProperties) SpringContextUtil.getInstance().getApplicationContext().getBean("jwtProperties");
	    //判断是否已登录
	    String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
	    if (StringUtils.isNotBlank(token)) {
	        //校验token令牌是否有效
	        try {
	            //根据公钥，解析token，获取授权用户信息
	            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
	            //解析成功重新刷新token（延续token的失效时间）
	            String newToken = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
	            //更新cookie中的token
	            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), newToken,
	                    jwtProperties.getCookieMaxAge(), true);
	            request.setAttribute("userInfo", userInfo);
	        } catch (Exception e) {
	            log.debug("请求url={}登录已失效！", requestUrl);
	        }
	    }
	
	    chain.doFilter(req, res);
	}*/

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String contextPath = request.getContextPath();
		String requestUrl = request.getRequestURL().toString();
		String queryString = request.getQueryString();
		if (queryString != null)
			requestUrl = requestUrl + "?" + queryString;
		request.setAttribute("contextPath", contextPath);
		request.setAttribute("requestURL", requestUrl);
		chain.doFilter(req, res);
	}
}
